package com.chengliang.zuoye.service.impl;

import com.chengliang.zuoye.bean.Role;
import com.chengliang.zuoye.bean.User;
import com.chengliang.zuoye.mapper.MenuMapper;
import com.chengliang.zuoye.mapper.RoleMapper;
import com.chengliang.zuoye.mapper.UserMapper;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;

/**
 * 登录验证处理
 */
@Service
public class MyUserDetailsService implements UserDetailsService {

    private final Logger logger = LoggerFactory.getLogger(this.getClass());

    private final UserMapper userMapper;

    private final RoleMapper roleMapper;

    private final MenuMapper menuMapper;

    @Autowired
    public MyUserDetailsService(UserMapper userMapper, RoleMapper roleMapper, MenuMapper menuMapper) {
        this.userMapper = userMapper;
        this.roleMapper = roleMapper;
        this.menuMapper = menuMapper;
    }

    @Override
    public UserDetails loadUserByUsername(String s) throws UsernameNotFoundException {
        User user = userMapper.findUserByEmail(s);
        // 判断用户是否存在
        if(user == null) {
            throw new UsernameNotFoundException("用户名不存在");
        }
        //获取用户角色信息
        Role role = roleMapper.selectByPrimaryKey(user.getRoleId());
        user.setRole(role);
        logger.info("该用户登录"+user);
        return user;
    }

}
